import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 将json文档转换为excel
 * @author: kanggw
 * @date: 2023/11/27
 **/
public class Json2excel {

    /**
     * 读取本地json文件,生成excel
     */
    public static void  getJsonExcel() {

        //1. 读取本地文件,得到json文件
        FileReader fileReader = new FileReader("/Users/kanggw/Documents/工作证明/2023年度打卡数据.json");

        String s = fileReader.readString();
        //2. 处理json文件,生成excel
        JSONObject jsonObject = JSONUtil.parseObj(s);

        JSONArray jsonArray = jsonObject.getJSONObject("data")
                                        .getJSONArray("data");

        List<Map<String,Object>> sheets = Lists.newArrayList();
        jsonArray.forEach(item -> {
            HashMap<String, Object> hashMap = Maps.newHashMap();
            hashMap.put("日期",LocalDateTimeUtil.parse(((JSONObject) item).getStr("day"), "yyyy-MM-dd"));
            hashMap.put("类型",((JSONObject) item).getStr("subTitle"));
            JSONArray array = ((JSONObject) item).getJSONArray("schdultTask");
            if (CollectionUtil.isEmpty(array)) {
                sheets.add(hashMap);
                return;
            }
            JSONArray records = ((JSONObject) array.get(0)).getJSONArray("records");
            if (CollectionUtil.isEmpty(records)) {
                sheets.add(hashMap);
                return;
            }
            try {
                Object o = ((JSONArray)records.get(0)).get(0);
                String start = ((JSONObject) o).getStr("time");
                hashMap.put("开始时间", LocalDateTimeUtil.parse(start, "HH:mm"));
            } catch (Exception e) {
                System.out.println("没有开始时间");
            }
            try {
                Object o1 = ((JSONArray) records.get(0)).get(1);
                String end = ((JSONObject) o1).getStr("time");
                hashMap.put("结束时间", LocalDateTimeUtil.parse(end, "HH:mm"));
            } catch (Exception e) {
                System.out.println("没有结束时间");
            }
            sheets.add(hashMap);
            });
        ExcelWriter writer = ExcelUtil.getWriter("/Users/kanggw/Documents/工作证明/2023年度打卡数据.xlsx");
        writer.write(sheets);
        writer.close();

    }

    public static void main(String[] args) {
        getJsonExcel();
    }
}
